rm(list = ls(all = TRUE)) #limpiar workspace

# ---------
# Read data
# ---------
setwd("~/Dropbox/DATA/DIPUTADOS_DISTRITO")
data <- lapply(list.files(), read.table, header=TRUE, sep="\t")
names(data) <- seq(1991, 2012, 3)
sapply(data, nrow)
lapply(data, names)

# ----------
# Clean data
# ----------
# 1991...ok
# 1994...ok
# 1997...PT gana un distrito
# 2000...Coaliciones:
data$"2000"$PAN <- data$"2000"$AC
data$"2000"$PRD <- data$"2000"$AM
# 2003... Coalición parcial PRI-PVEM
data$"2003"$PRI <- rowSums(data$"2003"[,c("PRI","APT")], na.rm=TRUE)
# 2006... Coaliciones:
data$"2006"$PRI <- data$"2006"$ALIANZA.POR.MÉXICO
data$"2006"$PRD <- data$"2006"$POR.EL.BIEN.DE.TODOS
# 2009... Coalicion parcial PRI-PVEM
data$"2009"$PRI <- rowSums(data$"2009"[,c("PRI","PRIMERO.MÉXICO")], na.rm=TRUE)
# 2012... Coaliciones parciales/totales:
data$"2012"$PRI <- rowSums(data$"2012"[,c("PRI","COALICIÓN.PRI.PVEM")], na.rm=TRUE)
data$"2012"$PRD <- rowSums(data$"2012"[,c("PRD","COALICIÓN.PRD.PT.MC","COALICIÓN.PRD.PT","COALICIÓN.PRD.MC")], na.rm=TRUE)
# Partidos relevantes, total, lista nominal
data <- lapply(data, function(x) x[,c("PAN","PRI","PRD")])

# --------------
# Indice de gini
# --------------
require(ineq)
library(RColorBrewer)

# *ignore warnings
sapply(data, function(x) ineq(as.numeric(x[,"PAN"]), type="Gini"))
sapply(data, function(x) ineq(as.numeric(x[,"PRI"]), type="Gini"))
sapply(data, function(x) ineq(as.numeric(x[,"PRD"]), type="Gini"))

# plot function
plot.Gini <- function(data, party, pal) {
  col <- brewer.pal(length(data), pal)
  plot(Lc(data[[1]][, party]), main=party, col=NULL)
  sapply(1:length(data), function(x) lines(Lc(data[[x]][,party]), col=col[x]))
}

setwd("~/REDISTRICTING/CURVAS_LORENZ")
pdf("gini.pdf", 9,3)
par(mfrow=c(1,3))
  plot.Gini(data, "PAN", "Purples")
  plot.Gini(data, "PRI", "Reds")
  plot.Gini(data, "PRD", "YlOrBr")
dev.off()
